import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    children: [
    ]
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/views/admin/Admin.vue'),
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/admin/Dashboard.vue')
      },
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('@/views/admin/UserManagement.vue')
      },
      {
        path: 'study-room',
        name: 'StudyRoomManagement',
        component: () => import('@/views/admin/StudyRoomManagement.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'feedback',
        name: 'FeedbackManagement',
        component: () => import('@/views/admin/FeedbackManagement.vue'),
        meta: { title: '留言管理', requiresAuth: true }
      },
      {
        path: 'announcement',
        name: 'AnnouncementManagement',
        component: () => import('@/views/admin/AnnouncementManagement.vue')
      },
      {
        path: 'snack',
        name: 'SnackManagement',
        component: () => import('@/views/admin/SnackManagement.vue')
      },
      {
        path: 'order',
        name: 'OrderManagement',
        component: () => import('@/views/admin/OrderManagement.vue')
      },
      {
        path: 'reservation',
        name: 'ReservationManagement',
        component: () => import('@/views/admin/ReservationManagement.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router 